package com.whfc.mach.xxl.job;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.whfc.XxlJobConfig;
import com.whfc.mach.dao.AppMachDataMapper;
import com.whfc.mach.manager.ObdDataMgr;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author sun_guodong
 * @description 刷新硬件在线状态
 * @date 2021-03-08
 */
@Component
@ConditionalOnBean(XxlJobConfig.class)
public class RefreshNetStateJob {
    @Autowired
    private ObdDataMgr obdDataMgr;

    @Autowired
    private AppMachDataMapper appMachDataMapper;

    /**
     * 参数名称
     */
    private static final String PARAM_NAME = "deptIds";

    /**
     * 刷新obd设备在线状态
     */
    @XxlJob("refreshObdNetState")
    public void refreshObdNetState() {
        String param = XxlJobHelper.getJobParam();
        XxlJobHelper.log("刷新OBD设备在线状态任务param:{}", param);
        try {
            List<Integer> deptIds = new ArrayList<>();
            JSONObject jsonObject = null;
            if (StringUtils.isNotEmpty(param)) {
                jsonObject = JSONObject.parseObject(param);
            }
            if (jsonObject != null) {
                JSONArray deptIdsJson = jsonObject.getJSONArray(PARAM_NAME);
                if (deptIdsJson != null) {
                    deptIds = deptIdsJson.toJavaList(Integer.class);
                }
            }
            XxlJobHelper.log("设备刷新obd硬件在线状态服务");
            Date time = new Date();
            List<Integer> machIds = appMachDataMapper.selectObdNetState2OfflineMachList(deptIds);
            int count = appMachDataMapper.batchUpdateObdNetStateOffline(machIds);
            for (Integer machId : machIds) {
                try {
                    obdDataMgr.addOfflineData(machId, time);
                } catch (Exception e) {
                    XxlJobHelper.log("添加离线数据点错误,machId:{},e:{}", machId, e);
                    continue;
                }
            }
            XxlJobHelper.log("本次obd设备离线数量:{}", count);
        } catch (Exception e) {
            XxlJobHelper.handleFail("刷新OBD设备在线状态任务,出现异常 error:" + e.getMessage());
        }
    }


}
